<template>
	<!-- 地址管理页面 -->
	<view id='address_manage_container'>
		<!-- 地址列表 -->
		<view class="address-list" v-if="addressList.length > 0">
			<view class="address-item" 
				v-for="(item, index) in addressList" 
				:key="item.id"
				>
				<view class="address-info" @click="selectAddress(item)">
					<view class="user-info">
						<text class="name">{{item.user_name}}</text>
						<text class="phone">{{item.tel_number}}</text>
						<view class="default-tag" v-if="item.default_address === 1">默认</view>
					</view>
					<view class="address-detail">
						<text>{{item.province_name}}{{item.city_name}}{{item.county_name}}{{item.detail_info}}</text>
					</view>
				</view>
				<view class="address-actions">
					<view class="action-item" @click="setDefaultAddress(item)">
						<view class="checkbox" :class="{ active: item.default_address === 1 }"></view>
						<text>默认地址</text>
					</view>
					<view class="operation">
						<view class="edit" @click="goToEdit(item)">
							<uni-icons type="compose" size="20" color="#666"></uni-icons>
							<text>编辑</text>
						</view>
						<view class="delete" @click="deleteAddress(item.id)">
							<uni-icons type="trash" size="20" color="#666"></uni-icons>
							<text>删除</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 空地址显示 -->
		<view class="empty-address" v-else>
			<image src="/static/images/empty-address.png" mode="aspectFit" class="empty-image"></image>
			<text class="empty-text">您还没有添加收货地址</text>
		</view>
		
		<!-- 添加新地址按钮 -->
		<view class="add-address" @click="goToAdd">
			<text class="add-text">添加收货地址</text>
		</view>
	</view>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import { onShow, onLoad } from "@dcloudio/uni-app"

// 地址列表
let addressList = ref([]);

// 标识是否仅管理地址 而非选择地址 （管理地址页面进来点击就不返回了）
let manageFlag = false;

onLoad((options)=>{
	if(options.flag == "1"){
		manageFlag = true;
	}else{
		manageFlag = false;
	}
})

onShow(()=>{
	getUserAddress();
})

// 获取用户所有收货地址
async function getUserAddress(){
	// 获取登录用户信息
	let userInfo = uni.getStorageSync("userInfo");
	let res = await uni.$http.get(`/user/getAddressList/${userInfo.user_id}`);
	if(res.data.code == 0){
		uni.$showT(res.data.msg);
		return 0;
	}
	
	addressList.value = res.data.data;
	checkHaveDefaultAddress(addressList.value);
	
	// console.log("用户地址列表", addressList.value);
}

// 检查是否有默认地址，如果没有默认地址，将第一条收货地址设为默认
function checkHaveDefaultAddress(){
	// 判断是否有收货地址
	if(addressList.value.length == 0){
		// console.log("没有地址，直接返回--");
		return 1;
	}
	
	// 检查列表中是否有默认地址
	let haveDefailt = false;
	for(let item of addressList.value){
		if(item.default_address == 1){
			haveDefailt = true;
		}
	}
	
	// 取出第一条的ID，调用设置默认的方法
	if(!haveDefailt){
		setDefaultAddress(addressList.value[0]);
	}
}

// 选择地址
function selectAddress(address) {
	// 在管理地址页面，忽略点击
	if(manageFlag){
		uni.$showT(`你好，${address.user_name}`)
		return 1;
	}
	// 将选择的地址存到localstorage
	uni.setStorageSync("address", JSON.stringify(address));
	uni.navigateBack();
}

// 跳转到添加地址页面
async function goToAdd() {
	// 检查token状态
	let res = await uni.$checkToken();
	if(!res){return 0;}
	
	uni.navigateTo({
		url: '/subPkg1/address_select/address_select'
	});
}

// 跳转到编辑地址页面
function goToEdit(address) {
	// 将需要编辑的收货地址数据进行存储，渲染到表单上
	uni.setStorageSync("editAddressInfo", address)
	uni.navigateTo({
		url: `/subPkg1/address_select/address_select?ops=edit`
	});
}

// 设置默认地址
async function setDefaultAddress(address) {
	
	if (address.default_address === 1) return;
	
	try {
		uni.showLoading({
			title: '设置中...'
		});
		
		let userInfo = uni.getStorageSync("userInfo");
		// console.log(address);
		// console.log(userInfo);
		let res = await uni.$http.put(`/address/setDefault/${address.id}/${userInfo.user_id}`);
		
		uni.hideLoading();
		uni.$showT(res.data.msg);
		
		if(res.data.code == 0){
			return 0;
		}
		
		getUserAddress();
		
	} catch (e) {
		console.error(e);
		uni.$showT('网络异常，请稍后重试');
	} finally {
		uni.hideLoading();
	}
}

// 删除地址
function deleteAddress(id) {
	uni.showModal({
		title: '提示',
		content: '确定要删除这个地址吗？',
		success: async function(res) {
			if (res.confirm) {
				try {
					uni.showLoading({
						title: '删除中...'
					});
					
					let userInfo = uni.getStorageSync("userInfo");
					let result = await uni.$http.delete(`/address/delete/${id}`);
					
					if (result.data.code == 1) {
						// 从本地移除
						getUserAddress();
						uni.$showT('删除成功');
					} else {
						uni.$showT(result.data.msg || '删除失败');
					}
				} catch (e) {
					console.error(e);
					uni.$showT('网络异常，请稍后重试');
				} finally {
					uni.hideLoading();
				}
			}
		}
	});
}
</script> 

<style lang ='scss' scoped>
#address_manage_container {
	min-height: 100vh;
	background-color: #f5f5f5;
	padding-bottom: 120rpx;
	position: relative;
	
	.header {
		height: 100rpx;
		background-color: #ffffff;
		display: flex;
		align-items: center;
		justify-content: center;
		position: sticky;
		top: 0;
		z-index: 10;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		
		.title {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
		}
	}
	
	.address-list {
		padding: 20rpx;
		
		.address-item {
			background-color: #ffffff;
			border-radius: 16rpx;
			margin-bottom: 20rpx;
			padding: 30rpx;
			box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
			
			.address-info {
				border-bottom: 1px solid #f0f0f0;
				padding-bottom: 20rpx;
				
				.user-info {
					display: flex;
					align-items: center;
					margin-bottom: 16rpx;
					
					.name {
						font-size: 32rpx;
						font-weight: bold;
						color: #333;
						margin-right: 20rpx;
					}
					
					.phone {
						font-size: 28rpx;
						color: #666;
					}
					
					.default-tag {
						margin-left: auto;
						background-color: #ff5500;
						color: #fff;
						font-size: 24rpx;
						padding: 4rpx 12rpx;
						border-radius: 6rpx;
					}
				}
				
				.address-detail {
					font-size: 28rpx;
					color: #666;
					line-height: 1.4;
				}
			}
			
			.address-actions {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding-top: 20rpx;
				
				.action-item {
					display: flex;
					align-items: center;
					
					.checkbox {
						width: 36rpx;
						height: 36rpx;
						border-radius: 50%;
						border: 2rpx solid #ddd;
						margin-right: 12rpx;
						position: relative;
						
						&.active {
							background-color: #ff5500;
							border-color: #ff5500;
							
							/* &::after {
								content: '';
								position: absolute;
								top: 8rpx;
								left: 12rpx;
								width: 12rpx;
								height: 20rpx;
								border-right: 4rpx solid #fff;
								border-bottom: 4rpx solid #fff;
								transform: rotate(45deg);
							} */
						}
					}
					
					text {
						font-size: 28rpx;
						color: #666;
					}
				}
				
				.operation {
					display: flex;
					
					.edit, .delete {
						display: flex;
						align-items: center;
						margin-left: 30rpx;
						
						text {
							font-size: 28rpx;
							color: #666;
							margin-left: 8rpx;
						}
					}
				}
			}
		}
	}
	
	.empty-address {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;
		
		.empty-image {
			width: 200rpx;
			height: 200rpx;
			margin-bottom: 30rpx;
		}
		
		.empty-text {
			font-size: 30rpx;
			color: #999;
		}
	}
	
	.add-address {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 100rpx;
		background-color: #ff5500;
		display: flex;
		align-items: center;
		justify-content: center;
		
		.add-text {
			font-size: 32rpx;
			color: #ffffff;
			font-weight: 500;
		}
	}
}
</style>